#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymongo
import os
from config import *
client=pymongo.MongoClient(MONGO_URL);
db=client["zhihu"];
import pandas as pd
import numpy as np
import matplotlib.pyplot as plot
import pyecharts as pc
#指定默认字体
plot.style.use('ggplot')
plot.rcParams['font.sans-serif'] = ['SimHei']
plot.rcParams['font.family']='sans-serif'



def get_data():
    queryArgs = {}
    projectionFields = {'_id': False}  # 用字典指定
    result = db["users"].find(queryArgs,projectionFields)
    return result

def filter_data(str):
    res="未知"
    if str==None or str=="":
        res="未知"
    else:
        res=str
    return res

def get_dx(str):
    res=""
    if str =="广州市":
        res="广州"
    else:
        res=str

    return res

def filter_location(str):
    location="未知"
    if str==None or len(str)==0:
        return location
    else:
        ss=str[0]
        if ss:
            location=ss.get("name","未知")
    print(location)
    return location

def main():
    data=pd.DataFrame(list(get_data()))
    # data=pd.DataFrame(data,index=data.index,columns=["name","education","gender","locations","employments"])
    # gender(data)
    # data["location"]=data["location"].apply(get_dx)

    location_se(data)
    print(data.head())




    print(len(data))


def location_se(data):
    location = data.groupby(by="business").size()
    location = location.sort_values(ascending=False)
    location = location.head(12)
    bar = pc.Bar("用户所在行业")
    bar.add("", location.index, location.values,xaxis_rotate=30)
    bar.render()
    return location


def gender(data):
    data["gender"]=data["gender"].apply(get_gender)
    genders = get_gender_per(data)
    lables = genders.keys()
    pers = genders.values()
    pie = pc.Pie("用户性别比例")
    pie.add("", lables, pers, is_label_show=True)
    pie.render()


def get_gender_per(re):
    gender={}
    dds=list(re["gender"])
    for dd in dds:
        if gender.get(dd):
            gender[dd]=gender.get(dd)+1
        else:
            gender[dd]=1
    sum=0
    for v in gender.values():
        sum+=v
    for k,v in gender.items():
        gender[k]='%.2f' % (v/sum)
    return gender


def get_gender(res):
    result="未知"
    if res==0:
        result="女"
    elif res==1:
        result="男"
    else:
        result="未知"
    return result
if __name__ == '__main__':
    main()